#!/usr/bin/env python

# Copyright 2006-2007 Scott Horowitz
# Licensed under the GPL

import urllib2, urllib

def download_image_to_filename(artist, album, dest_filename): 
    # Returns False if no images found
    imgfound = False
    img_url = ""
    # Amazon currently doesn't support utf8 and suggests latin1 encoding instead:
    try:
        artist = urllib.quote(artist.encode('latin1'))
        album = urllib.quote(album.encode('latin1'))
    except:
        artist = urllib.quote(artist)
        album = urllib.quote(album)
    amazon_key = "12DR2PGAQT303YTEWP02"
    search_url = "http://webservices.amazon.com/onca/xml?Service=AWSECommerceService&AWSAccessKeyId=" \
                 + amazon_key \
                 + "&Operation=ItemSearch&SearchIndex=Music&Artist="\
                 + artist \
                 + "&ResponseGroup=Images&Keywords=" \
                 + album
    request = urllib2.Request(search_url)
    opener = urllib2.build_opener()
    f = opener.open(request).read()
    curr_pos = 300    # Skip header..
    curr_pos = f.find("<LargeImage>", curr_pos+10)
    url_start = f.find("<URL>http://", curr_pos)+len("<URL>")
    url_end = f.find("</URL>", curr_pos)
    img_url = f[url_start:url_end]
    urllib.urlretrieve(img_url, dest_filename)
    imgfound = True
    return imgfound

if __name__ == "__main__":
    import sys
    try:
        artist = sys.argv[1]
        album = sys.argv[2]
        outfile = sys.argv[3]
    except:
        print 'Usage: %s artist album outfile' % sys.argv[0]
        sys.exit(1)
    res = download_image_to_filename(artist, album, outfile)
    print res
